package com.ctrip.corp.obt.shard.aop.shard;

import com.ctrip.corp.obt.generic.core.context.TenantContext;
import com.ctrip.corp.obt.generic.utils.Conditional;
import com.ctrip.corp.obt.shard.configuration.DataShardProperties;
import com.ctrip.corp.obt.shard.handler.IShardingHandler;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @author marco.zheng
 * @version 1.0
 * @date 2022/02/09
 * @desc 根据用户配置的shard策略进行shard
 * @see
 * @since 1.0
 */
public class ShardInfoDSAspect extends AbstractDataShardAspect implements Filter {

    public ShardInfoDSAspect(IShardingHandler shardingHandler, DataShardProperties dataShardProperties) {
        super(shardingHandler);
        this.dataShardProperties = dataShardProperties;
    }

    private final DataShardProperties dataShardProperties;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String tenantId = TenantContext.getTenantId();
        // 获取用户配置的shard策略
        String tableShardStrategy = Conditional.ofNullable(getTableShardStrategy(tenantId)).orElse(dataShardProperties.getGlobalTableShardStrategy());
        preShard(tableShardStrategy);
        chain.doFilter(request, response);
    }

    private String getTableShardStrategy(String tenantId) {
        // TODO 获取用户配置的shard策略
        return null;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
